<?php
class CartModel extends Model
{
    /**
     * @var Session
     */
    protected $_session = null;

    public function __construct()
    {
        parent::__construct();

        $this->_session = Loader::getInstance()->library('session');
    }

    public function getCart()
    {
        $cart = $this->_session->get('cart');

        return is_array($cart)? $cart : array();
    }

    public function setCart($cart)
    {
        $this->_session->set('cart', $cart);
    }

    public function deleteCart()
    {
        $this->setCart(array());
    }

    public function delete($itemId)
    {
        $cart = $this->getCart();

        unset($cart[$itemId]);

        $this->setCart($cart);
    }

    public function updateItem(array $item)
    {
        $cart = $this->getCart();

        // Item already exists, only update the quantity
        if (isset($cart[$item['id']]))
        {
            $cart[$item['id']]['quantity']++;
        }
        // Item doest not exist, simply insert into the cart
        else
        {
            $cart[$item['id']] = $item;
        }

        $this->setCart($cart);
    }

    public function updateQuantity(array $quantities)
    {
        $cart = $this->getCart();

        foreach ($quantities as $itemId => $quantity)
        {
            if ($quantity <= 0)
            {
                unset($cart[$itemId]);
            }
            else
            {
                $cart[$itemId]['quantity'] = $quantity;
            }
        }

        $this->setCart($cart);
    }
}